<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class="post-btn"
      :disabled="!message.length"
      @click="submit"
    >发布</van-button>
  </div>
</template>

<script>
import { addComment } from '@/api/comment'
export default {
  name: 'CommentPost',
  props: {
    // 目标ID
    targetId:{
      type:[Number,String,Object],
      require:true
    },
    // 列表数据
    list:{
      type:Array,
      require:true
    },
    // 文章ID
    articleId:{
      type:[Object,String,Number],
      default:null
    }
  },
  data () {
    return {
      message: ''  // 输入框的数据
    }
  },
  methods: {
    // 提交事件
    async submit(){
      this.$toast.loading({
        forbidClick:true,
        duration:0,
        message:'发布中...'
      })
      try {
        let {data:res} = await addComment({
          target:this.targetId.toString(), // 目标Id，文章评论则传文章ID，评论回复传评论ID
          content:this.message, // 评论信息
          art_id:this.articleId // 文章ID， 对 评论回复则需要传递，对文章评论不需要
        })
        this.$toast.success('发布成功')
        this.message = ''
        // 将数据插入到列表中
        this.list.unshift(res.data.new_obj)
        // 关闭弹出层
        this.$emit('close')
      } catch (error) {
        console.log(error);
        this.$toast.fail('发布失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
